package com.carlos.company.security.handler;

import com.carlos.company.security.JsonAuthentication;
import com.carlos.company.vo.ResultCode;
import com.carlos.company.vo.ResultVO;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Carlos Li
 * @date 2021/5/22
 */

@Component("myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        ResultVO<Void> result;
        if (e instanceof AccountExpiredException) {
            //账号过期
            result = new ResultVO<Void>().fail(ResultCode.USER_ACCOUNT_EXPIRED.getMessage());
        } else if (e instanceof UsernameNotFoundException) {
            //用户不存在
            result = new ResultVO<Void>().fail(ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        } else if (e instanceof CredentialsExpiredException) {
            //密码过期
            result = new ResultVO<Void>().fail(ResultCode.USER_CREDENTIALS_EXPIRED.getMessage());
        } else if (e instanceof DisabledException) {
            //账号不可用
            result = new ResultVO<Void>().fail(ResultCode.USER_ACCOUNT_DISABLE.getMessage());
        } else if (e instanceof LockedException) {
            //账号锁定
            result = new ResultVO<Void>().fail(ResultCode.USER_ACCOUNT_LOCKED.getMessage());
        } else if (e.getClass() == BadCredentialsException.class) {

            //密码错误
            System.out.println("啊哈哈哈");
            result = new ResultVO<Void>().fail(ResultCode.USER_CREDENTIALS_ERROR.getMessage());
        }else{
            //其他错误
            result = new ResultVO<Void>().fail(ResultCode.COMMON_FAIL.getMessage());
        }

        JsonAuthentication.writeJson(httpServletRequest,httpServletResponse,result);
    }
}
